// Top10Mapper.java
package com.taxi.analysis.regionTop10;

import java.io.IOException;
import java.util.TreeMap;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

public class Top10Mapper extends Mapper<LongWritable, Text, NullWritable, Text> {

    private TreeMap<Integer, String> top10Map = new TreeMap<>();

    @Override
    public void map(LongWritable key, Text value, Context context)
            throws IOException, InterruptedException {

        try {
            String line = value.toString().trim();
            String[] parts = line.split("	");

            if (parts.length == 2) {
                String region = parts[0];
                int count = Integer.parseInt(parts[1]);

                // 维护TOP10
                top10Map.put(count, region);

                // 保持只有前10个
                if (top10Map.size() > 10) {
                    top10Map.remove(top10Map.firstKey());
                }
            }
        } catch (Exception e) {
            System.err.println("Error processing: " + value.toString());
        }
    }

    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        // 输出TOP10，按降序排列
        for (int count : top10Map.descendingKeySet()) {
            String region = top10Map.get(count);
            context.write(NullWritable.get(),
                    new Text(region + "	" + count));
        }
    }
}
